$(document).ready(function() {

    if(sessionStorage.getItem("adminAccount")==null){
        location.href="AdminLogin"
    }
    //
    // $(".logout-btn").click(function() {
    //     if (confirm("确定要退出登录吗？")) {
    //         // 这里实际项目中应该是跳转到登录页
    //         showNotification("您已安全退出系统", 'success');
    //
    //         // 模拟退出效果
    //         setTimeout(() => {
    //             $(".user-info").fadeOut(500);
    //             showNotification("请重新登录系统", 'info');
    //         }, 1500);
    //     }
    // });



    // 示例学生数据
    let students = [];
    // 分页相关变量
    let currentPage = 1;
    let rowsPerPage = parseInt($("#rows-per-page").val());


    $.ajax({
        url:"/teacher/SearchTeachers",
        type:"POST",
        async:false,
        data:{
            page:currentPage,
            pageSize:rowsPerPage,
        },
        success:function(value){
            students=value.data
        },
        error:function(){
            alert("请求失败了")
        }
    })
    let filteredStudents = students;


    // 渲染学生表格
    function renderStudentTable() {
        const tbody = $("#student-table tbody");
        tbody.empty();

        // 计算当前页的数据
        const startIndex = (currentPage - 1) * rowsPerPage;
        const endIndex = Math.min(startIndex + rowsPerPage, filteredStudents.length);
        const currentStudents = filteredStudents.slice(startIndex, endIndex);

        // 更新分页信息
        $("#start-row").text(startIndex + 1);
        $("#end-row").text(endIndex);
        $("#total-rows").text(filteredStudents.length);

        if (currentStudents.length === 0) {
            tbody.html(`
                        <tr>
                            <td colspan="7">
                                <div class="empty-state">
                                    <i class="fas fa-inbox"></i>
                                    <h3>没有找到教师信息</h3>
                                    <p>尝试添加新教师或修改搜索条件</p>
                                </div>
                            </td>
                        </tr>
                    `);
            return;
        }

        currentStudents.forEach(student => {

            const row = `
                        <tr>
                            <td class="student-id">${student.id}</td>
                            <td>${student.name}</td>
                            <td>${student.password}</td>
                            <td>${student.age}</td>
                            <td>${student.sex}</td>
                            <td>${student.workNumber}</td>
                            <td>${student.phone}</td>
                            <td class="actions">
                                <div class="action-btn edit-btn" data-id="${student.id}" title="编辑">
                                    <i class="fas fa-edit"></i>
                                </div>
                                <div class="action-btn delete-btn" data-id="${student.id}" title="删除">
                                    <i class="fas fa-trash"></i>
                                </div>
                            </td>
                        </tr>
                    `;
            tbody.append(row);
        });

        // 渲染分页控件
        renderPagination();
    }

    // 渲染分页控件
    function renderPagination() {
        const totalPages = Math.ceil(filteredStudents.length / rowsPerPage);

        // 清空现有的页码按钮
        $(".pagination-controls .pagination-btn:not(.first-page):not(.prev-page):not(.next-page):not(.last-page)").remove();

        // 确定要显示的页码范围
        let startPage = Math.max(1, currentPage - 2);
        let endPage = Math.min(totalPages, startPage + 4);

        if (endPage - startPage < 4) {
            startPage = Math.max(1, endPage - 4);
        }

        // 添加上一页按钮
        $(".prev-page").after($(".prev-page").next(".pagination-btn").detach());

        // 添加页码按钮
        for (let i = endPage; i >= startPage; i--) {
            const pageBtn = $(`<div class="pagination-btn" data-page="${i}">${i}</div>`);
            if (i === currentPage) {
                pageBtn.addClass("active");
            }

            $(".prev-page").after(pageBtn);
        }

        // 更新按钮状态
        $(".first-page").toggleClass("disabled", currentPage === 1);
        $(".prev-page").toggleClass("disabled", currentPage === 1);
        $(".next-page").toggleClass("disabled", currentPage === totalPages);
        $(".last-page").toggleClass("disabled", currentPage === totalPages);
    }

    // 初始化表格
    renderStudentTable();

    // 打开添加模态框
    $("#add-btn").click(function() {
        $("#add-modal").css("display", "flex");
        $("#student-name").focus();
    });

    // 关闭所有模态框
    function closeAllModals() {
        $(".modal").hide();
    }

    // 关闭模态框
    $(".close-btn, #cancel-add, #cancel-edit").click(closeAllModals);

    // 点击模态框外部关闭
    $(document).click(function(e) {
        if ($(e.target).hasClass('modal')) {
            closeAllModals();
        }
    });

    // 保存新学生
    $("#save-add").click(function() {
        const name = $("#student-name").val().trim();
        const phone = $("#student-phone").val().trim();
        const password = $("#student-password").val().trim();
        const age = $("#student-age").val().trim();
        const sex = $("#student-sex").val().trim();
        const workNumber = $("#student-workNumber").val().trim();

        if (!name || !phone) {
            alert("请填写所有必填字段");
            return;
        }

        if (!/^1[3-9]\d{9}$/.test(phone)) {
            alert("请输入有效的手机号码");
            return;
        }

        $.ajax({
            url:"/teacher/AddTeacher",
            type:"POST",
            async:false,
            data:{
                name: name,
                phone: phone,
                password,
                age,
                sex,
                workNumber
            },
            success:function(value){
                console.log(value)
            },
            error:function(){
                alert("请求失败了")
            }
        })


        // 重置到第一页
        currentPage = 1;

        // 重新渲染表格
        renderStudentTable();

        // 关闭模态框并清空表单
        $("#add-modal").hide();
        $("#student-name, #student-class, #student-phone").val("");

        // 显示成功消息
        showNotification(`教师 <strong>${name}</strong> 添加成功！`, 'success');
    });

    // 搜索功能
    $("#search-btn").click(function() {
        const name = $("#name-search").val().toLowerCase();
        const phone = $("#phone-search").val().toLowerCase();
        const workNumber = $("#workNumber-search").val().toLowerCase();

        filteredStudents = students.filter(student => {
            return (name === "" || student.name.toLowerCase().includes(name)) &&
                (phone === "" || student.phone.toLowerCase().includes(phone))&&
                (workNumber === "" || student.workNumber.includes(workNumber));
        });

        // 重置到第一页
        currentPage = 1;

        renderStudentTable();

        // 显示搜索结果消息
        if (filteredStudents.length === 0) {
            showNotification("没有找到匹配的教师", 'warning');
        } else {
            showNotification(`找到 ${filteredStudents.length} 名教师`, 'success');
        }
    });

    // 按回车键触发搜索
    $("#name-search, #class-search, #phone-search").keypress(function(e) {
        if (e.which === 13) {
            $("#search-btn").click();
        }
    });

    // 删除学生
    $(document).on("click", ".delete-btn", function() {
        const id = $(this).data("id");


        if (confirm(`确定要删除该教师吗？此操作不可恢复。`)) {
            $.ajax({
                url:"/teacher/DeleteTeacher",
                type:"POST",
                async:false,
                data:{
                    id
                },
                success:function(value){
                    location.reload()
                },
                error:function(){
                    alert("请求失败了")
                }
            })

            // 如果当前页没有数据且不是第一页，则回到上一页
            const startIndex = (currentPage - 1) * rowsPerPage;
            if (startIndex >= filteredStudents.length && currentPage > 1) {
                currentPage--;
            }

            renderStudentTable();
            showNotification(`教师已删除`, 'error');
        }
    });

    // 编辑学生 - 打开模态框
    $(document).on("click", ".edit-btn", function() {
        const id = $(this).data("id");
        const student = students.find(s => s.id === id);

        if (student) {
            // 填充表单数据
            $("#edit-id").val(student.id);
            $("#edit-name").val(student.name);
            $("#edit-phone").val(student.phone);
            $("#edit-age").val(student.age);
            $("#edit-sex").val(student.sex);
            $("#edit-workNumber").val(student.workNumber);
            $("#edit-password").val(student.password);

            // 显示编辑模态框
            $("#edit-modal").css("display", "flex");
        }
    });

    // 保存编辑
    $("#save-edit").click(function() {
        const id = parseInt($("#edit-id").val());
        const name = $("#edit-name").val().trim();
        const phone = $("#edit-phone").val().trim();
        const age = $("#edit-age").val().trim();
        const sex = $("#edit-sex").val().trim();
        const workNumber = $("#edit-workNumber").val().trim();
        const password = $("#edit-password").val().trim();

        if (!name || !phone) {
            alert("请填写所有必填字段");
            return;
        }

        if (!/^1[3-9]\d{9}$/.test(phone)) {
            alert("请输入有效的手机号码");
            return;
        }

        // 更新学生信息
        const studentIndex = students.findIndex(s => s.id === id);
        const filteredIndex = filteredStudents.findIndex(s => s.id === id);

        if (studentIndex !== -1) {
            $.ajax({
                url:"/teacher/UpdateTeacher",
                type:"POST",
                async:false,
                data:{
                    id,
                    name,
                    phone,
                    age,
                    sex,
                    password,
                    workNumber
                },
                success:function(value){
                    location.reload()
                },
                error:function(){
                    alert("请求失败了")
                }
            })

            // 重新渲染表格
            renderStudentTable();

            // 关闭模态框
            $("#edit-modal").hide();

            // 显示成功消息
            showNotification(`教师 <strong>${name}</strong> 信息已更新`, 'success');
        }
    });

    // 分页事件处理
    $(document).on("click", ".pagination-btn", function() {
        if ($(this).hasClass("disabled")) return;

        const totalPages = Math.ceil(filteredStudents.length / rowsPerPage);

        if ($(this).hasClass("first-page")) {
            currentPage = 1;
        } else if ($(this).hasClass("prev-page")) {
            if (currentPage > 1) currentPage--;
        } else if ($(this).hasClass("next-page")) {
            if (currentPage < totalPages) currentPage++;
        } else if ($(this).hasClass("last-page")) {
            currentPage = totalPages;
        } else {
            currentPage = parseInt($(this).data("page"));
        }

        renderStudentTable();
    });

    // 每页显示行数更改
    $("#rows-per-page").change(function() {
        rowsPerPage = parseInt($(this).val());
        currentPage = 1;
        renderStudentTable();
    });

    // 显示通知函数
    function showNotification(message, type) {
        // 移除之前的通知
        $(".notification").remove();

        const notification = $(`
                    <div class="notification" style="
                        position: fixed;
                        top: 20px;
                        right: 20px;
                        padding: 15px 25px;
                        border-radius: 8px;
                        color: white;
                        font-weight: 600;
                        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                        z-index: 2000;
                        display: flex;
                        align-items: center;
                        gap: 10px;
                        animation: fadeIn 0.3s, fadeOut 0.3s 2.7s;
                    ">
                        <i class="fas ${type === 'success' ? 'fa-check-circle' : type === 'error' ? 'fa-exclamation-circle' : 'fa-info-circle'}"></i>
                        <span>${message}</span>
                    </div>
                `);

        // 设置背景颜色
        if (type === 'success') {
            notification.css('background', 'linear-gradient(to right, #34a853, #2d9248)');
        } else if (type === 'error') {
            notification.css('background', 'linear-gradient(to right, #ea4335, #d32a1c)');
        } else {
            notification.css('background', 'linear-gradient(to right, #fbbc05, #e0a800)');
        }

        // 添加到页面
        $("body").append(notification);

        // 5秒后移除
        setTimeout(() => {
            notification.remove();
        }, 3000);
    }
});